'use strict';
const db = uniCloud.database();
exports.main = async (event, context) => {
	if (event.user_type == 0) {
		//user_type = 0 发送验证码
		let res = await send_code(event)
		return res
	} else if (event.user_type == 1) {
		//user_type = 1 用户登录
		let res = await login_user(event)
		return res
	} else if (event.user_type == 2) {
		//user_type = 2 获取用户信息
		let res = await obtain_user(event)
		return res
	} else if (event.user_type == 3) {
		//user_type = 3 更新用户信息
		let res = await update_user(event)
		return res
	} else if (event.user_type == 4) {
		//user_type = 4 修改用户登录密码
		let res = await revise_password(event)
		return res
	}
};

//发送验证码之前验证
const send_code = async (event) => {
	let system = db.collection('system');
	let code = db.collection('code_list');
	let loginPhone = event.loginPhone;
	let create_time = new Date().getTime();
	let status = 0;
	//先检查是否有有效的验证码存在
	let code_s = await code.where({
		loginPhone: loginPhone,
		status: 0
	}).get();
	if (code_s.data.length > 0) {
		return {
			msg: '存在未失效的验证码,请查看手机短信'
		}
	} else {
		let code_key = await system.where({
			system_name: "send_code"
		}).get();
		let type = code_key.data[0].system_number[0]; //记录模板id
		let str = '',
			arr = '1234';
		for (let i in arr) {
			str += Math.floor(Math.random() * 10); //随机生成四个个位数拼接为验证码;
		}
		let obj = {
			loginPhone: loginPhone,
			create_time: create_time,
			status: status,
			type: type,
			code: str
		}
		let add_code = await code.add(obj);
		if (add_code) {
			obj.smsKey = code_key.data[0].system_smsKey; //记录短信模板key
			obj.smsSecret = code_key.data[0].system_smsSecret; //记录短信模板Secret
			return await code_send(obj)
		} else {
			return {
				msg: '验证码写入失败'
			}
		}
	}
}

// 验证码发送
const code_send = async (obj) => {
	try {
		const res = await uniCloud.sendSms({
			smsKey: obj.smsKey,
			smsSecret: obj.smsSecret,
			phone: obj.loginPhone,
			templateId: `${obj.type}`,
			data: {
				code: obj.code,
				expMinute: '60',
			}
		})
		// 调用成功，请注意这时不代表发送成功
		return res
	} catch (err) {
		return {
			code: err.errCode,
			msg: err.errMsg
		}
	}
}

//用户登录
const login_user = async (event) => {
	const code_list = db.collection('code_list');
	const userDetail = db.collection('user');
	const sign = db.collection('sign_in_user');
	let code_s = await code_list.where({
		loginPhone: event.loginPhone,
		code: event.code,
		status: 0
	}).count();
	if(code_s.total == 1){
		let code_u = await code_list.where({
			loginPhone: event.loginPhone,
			code: event.code,
			status: 0
		}).update({
			status: 1
		});
		if(code_u.updated == 1){
			let user_s = await userDetail.where({
				loginPhone: event.loginPhone
			}).count();
			if(user_s.total == 1){
				return await userDetail.where({loginPhone: event.loginPhone}).get()
			}else {
				delete event.code
				delete event.user_type
				delete event.uniIdToken
				return await create_user(event);
			}
		}else {
			return {
				msg: '验证码验证失败'
			}
		}
	}else {
		return {
			msg: '验证码错误'
		}
	}
}

const create_user = async (event) =>{
	const userDetail = db.collection('user');
	const sign = db.collection('sign_in_user');
	// 给未赋值的参数加入默认参数
	event.headImg= "http://zhizhen.oss-cn-beijing.aliyuncs.com/mall/images/20201112/1605169197670IMG_0557.jpg"; //头像
	event.gender = 0; //等级
	event.leavelId = 0;//性别
	event.leavelName = "普通会员"; //等级名称
	event.balance = 0; //余额
	event.integral = 0; //积分
	event.nickName = '用户' + event.loginPhone; //用户昵称
	event.couponCount = 0; //优惠券数量
	event.orderBalance = 0; //订单返利金额
	event.rechargeBalance = 0; //充值过的余额
	event.registerArea = ""; 
	event.registerCity = ""; //注册市
	event.registerCountry = "";//注册区
	event.registerDetailAddress = "";//注册具体地址
	event.registerEmail = "";//注册邮箱
	event.registerProvince = "";// 注册省
	event.shopBalance = 0; //总共购买金额
	event.shopIntegral = 0; //总共购买消耗积分
	event.signInDays = 0; //总共签到天数
	event.signIntegral = 0; //签到得到的积分
	event.userIntegral = 0;//邀请获得的积分
	event.withdrawalBalance = 0;//提现消耗的金额
	event.please_user_lBalance = 0; //邀请下级得到的返利余额
	event.pleaseCount = 0; //总共邀请的人数(包含注销的人数)
	const res2 = await userDetail.add(event); //添加注册用户
	if(event.invitecode != ''){
		const res3 = await userDetail.where({_id:event.invitecode}).get();
		let cc = res3.data[0].integral + 99;
		let dd = res3.data[0].userIntegral + 99;
		let ss = res3.data[0].pleaseCount + 1;
		const res4 = await userDetail.where({_id:event.invitecode}).update({
			integral: cc,
			userIntegral: dd,
			pleaseCount: ss
		})
		let result = await sign.add({
			user_id:event.invitecode,
			integral_number: 99,
			sign_time: event.createTime,
			type: 1,
			descration: '邀请好友获得积分'
		});
		return res2
	}else {
		return res2
	}
}

//获取用户信息
const obtain_user = async (event) => {
	const userDetail = db.collection('user');
	let res = await userDetail.where({
		_id: event._id
	}).get();
	return res
}

//更新用户信息
const update_user = async (event) => {
	const userDetail = db.collection('user');
	let user_id = event._id;
	delete event._id;
	delete event.user_type;
	let res = await userDetail.where({
		_id: user_id
	}).update(event);
	return res
}

//修改用户登录密码
const revise_password = async (event) => {
	const userDetail = db.collection('user');
	let res = await userDetail.where({
		_id: event._id
	}).update({
		loginPassWord: event.loginPassWord
	});
	return res
}
